package com.example.weworkfinancesdk.utils;


public final class Platform {

    private static String ARCH = System.getProperty("os.arch").toLowerCase();

    public static final int UNSPECIFIED = -1;
    public static final int LINUX = 1;
    public static final int WINDOWS = 2;
    public static final int WINDOWSCE = 6;
    public static final int ANDROID = 8;

    private static final int osType;

    public static final String RESOURCE_PREFIX;

    static {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Linux")) {
            if ("dalvik".equals(System.getProperty("java.vm.name").toLowerCase())) {
                osType = ANDROID;
            }
            else {
                osType = LINUX;
            }
        }
        else if (osName.startsWith("Windows CE")) {
            osType = WINDOWSCE;
        }
        else if (osName.startsWith("Windows")) {
            osType = WINDOWS;
        }
        else {
            osType = UNSPECIFIED;
        }

        RESOURCE_PREFIX = getNativeLibraryResourcePrefix();
    }

    public static final boolean isWindows() {
        return osType == WINDOWS || osType == WINDOWSCE;
    }

    public static final boolean isLinux() { return osType == LINUX; }

    public static boolean is64Bit() {
        if (ARCH.indexOf("sparcv9") >= 0) {
            return true;
        }
        return (ARCH.indexOf("64") > 0);
    }

    static String getNativeLibraryResourcePrefix() {
        String prefix = System.getProperty("jna.prefix");
        if(prefix != null) {
            return prefix;
        } else {
            return getNativeLibraryResourcePrefix(getOSType(), System.getProperty("os.arch"), System.getProperty("os.name"));
        }
    }

    public static final int getOSType() {
        return osType;
    }

    static String getNativeLibraryResourcePrefix(int osType, String arch, String name) {
        String osPrefix;
        arch = getCanonicalArchitecture(arch, osType);
        switch(osType) {
            case Platform.WINDOWS:
                osPrefix = "win32-" + arch;
                break;
            case Platform.LINUX:
                osPrefix = "linux-" + arch;
                break;
            default:
                osPrefix = name.toLowerCase();
                int space = osPrefix.indexOf(" ");
                if (space != -1) {
                    osPrefix = osPrefix.substring(0, space);
                }
                osPrefix += "-" + arch;
                break;
        }
        return osPrefix;
    }

    static String getCanonicalArchitecture(String arch, int platform) {
        arch = arch.toLowerCase().trim();
        if ("i386".equals(arch) || "i686".equals(arch)) {
            arch = "x86";
        }
        else if ("x86_64".equals(arch) || "amd64".equals(arch)) {
            arch = "x86-64";
        }
        return arch;
    }
}
